//
//  AFNetworkHelper.m
//  TableBarControllerDemo
//
//  Created by 边果互动 on 2021/3/17.
//

#import "AFNetworkHelper.h"
#import <AFNetworking/AFNetworking.h>
#import "FormatUtil.h"
#import "ImageUtil.h"
#import "SharePreferencesHelper.h"
#import "TextUtil.h"

@interface AFNetworkHelper()

@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, strong) SharePreferencesHelper *sph;

@end

@implementation AFNetworkHelper

+ (instancetype) defaultAFNetwork {
    return [self new];
}

#pragma mark - 单例模式
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static AFNetworkHelper *helper = nil;
    if (nil == helper) {
        helper = [super allocWithZone:zone];
        helper.manager = [AFHTTPSessionManager manager];
//        AFAppDotNetAPIClient *manager =  [AFAppDotNetAPIClient sharedClient];
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        helper.manager.requestSerializer = [AFJSONRequestSerializer serializer];
        helper.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
        // 设置超时时间
        [helper.manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        [helper.manager.requestSerializer  setValue:@"application/json"  forHTTPHeaderField:@"Content－Type"];
        helper.manager.requestSerializer.timeoutInterval = 15.f;
        [helper.manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        //获取保存的数据用的
        helper.sph = [SharePreferencesHelper defaultSph];
    }
    return helper;
}

#pragma mark - Post请求
- (void) postWithUrl: (NSString *) url andParams: (NSDictionary *) params andSucucess:(nonnull success)success andError:(nonnull failed)failed {
    if ([url hasPrefix:@"http"]) {
        
    } else {
        url = [NSString stringWithFormat:@"%@%@", BASE_URL, url];
    }
    NSMutableDictionary *dict = [params mutableCopy];
    NSString *token = [self.sph getToken];
    if (![TextUtil isEmpty:token]) {
        [dict setValue:token forKey:@"token"];
    }
    //这边固定一个token，防止外部请求接口
//    [dict setValue:@"dbac58fd32dbd5743a12" forKey:@"token"];
    //添加Header
    NSDictionary *header = @{
        @"Content-Typeype":@"application/json; charset=utf-8"
    };
    //开始POST请求
    [self.manager POST:url parameters:dict headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        MLog(@"POST\t%@\nrequest:%@\nresponse:%@", url, dict, responseObject);
        //表示接口请求成功，responseObjcet其实是一个字典
        //利用Block实现类似安卓的回调
        [self doSuccess:responseObject andSucucess:success andError:failed];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //表示接口请求错误
        //利用Block实现类似安卓的回调
        [self doFailure:error andError:failed];
    }];
}

#pragma mark - Get请求
- (void) getWithUrl: (NSString *) url andPararams: (NSDictionary *) params andSucucess:(nonnull success)success andError:(nonnull failed)failed {
    if ([url hasPrefix:@"http"]) {
        
    } else {
        url = [NSString stringWithFormat:@"%@%@", BASE_URL, url];
    }
    NSMutableDictionary *dict = [params mutableCopy];
    NSString *token = [self.sph getToken];
    if (![TextUtil isEmpty:token]) {
        [dict setValue:token forKey:@"token"];
    }
    //这边固定一个token，防止外部请求接口
//    [dict setValue:@"dbac58fd32dbd5743a12" forKey:@"token"];
    
    NSDictionary *header = @{
        @"Content-Typeype":@"application/json; charset=utf-8"
    };
    
    //开始GET请求
    [self.manager GET:url parameters:dict headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        MLog(@"GET\t%@\nrequest:%@\nresponse:%@", url, dict, responseObject);
        //表示接口请求成功，responseObjcet其实是一个字典
        //利用Block实现类似安卓的回调
        [self doSuccess:responseObject andSucucess:success andError:failed];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //表示接口请求错误
        //利用Block实现类似安卓的回调
        [self doFailure:error andError:failed];
    }];
}

# pragma mark - 上传图片
- (void) upload: (UIImage *) img andSuccess: (nonnull success) success andFailed:(nonnull failed) failed {
    NSString *url = [NSString stringWithFormat:@"%@%@", BASE_URL, @"/public/api/Upload/index"];
    NSDictionary *params = @{@"sign":@""};
    
//    [self.manager.requestSerializer setValue:@"multipart/form-data"  forHTTPHeaderField:@"Content－Type"];
    NSDictionary *header = @{
        @"Content-Typeype":@"multipart/form-data"
    };
    [self.manager POST:url parameters:params headers:header constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //表示添加文件信息
        //参数一：文件
        //参数二：接口参数
        //参数三：文件名
        //参数四：文件类型
        NSString *currentTime = [FormatUtil getCurrentTime:@"yyyyMMddHHmmss"];
        [formData appendPartWithFileData:[ImageUtil compressImage:img endValue:1] name:@"img" fileName:[NSString stringWithFormat:@"%@.jpg", currentTime] mimeType:@"image/jpg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //表示接口请求成功，responseObjcet其实是一个字典
        //利用Block实现类似安卓的回调
        [self doSuccess:responseObject andSucucess:success andError:failed];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //表示接口请求错误
        //利用Block实现类似安卓的回调
        [self doFailure:error andError:failed];
    }];
}

#pragma mark - 对请求成功的结果进行处理
- (void) doSuccess: (id  _Nullable) response andSucucess:(nonnull success)success andError:(nonnull failed)failed {
    //表示接口请求成功，responseObjcet其实是一个字典
    //利用Block实现类似安卓的回调
    //工具类获取返回值的status
    NSString *status = [FormatUtil encodeStringFromDic:response andKey:@"status"];
    if ([status isEqualToString:@"0"]) {
        //表示接口数据正常
        if (success) {
            success(response);
        }
    } else {
        //表示接口数据不对
        if (failed) {
            NSString *msg = [FormatUtil encodeStringFromDic:response andKey:@"msg"];
            failed(msg, status.intValue);
        }
    }
}

#pragma mark - 对请求出错的结果进行处理
- (void) doFailure: (NSError * _Nonnull) error andError:(nonnull failed)failed {
    //表示接口请求错误
    //利用Block实现类似安卓的回调
    if (failed) {
        failed(error.localizedFailureReason, error.code);
    }
}

@end
